package cn.orange.ch01_array.binarysearch;

import java.util.Arrays;

/**
 * LC34.在排序数组中查找元素的第一个和最后一个位置
 给你一个按照非递减顺序排列的整数数组 nums，和一个目标值 target。请你找出给定目标值在数组中的开始位置和结束位置。
 如果数组中不存在目标值 target，返回 [-1, -1]。
 你必须设计并实现时间复杂度为 O(log n) 的算法解决此问题
 */
public class LC34 {
    public int[] searchRange(int[] nums, int target) {
        int first = searchLeftMost(nums, target);
        int last = searchRightMost(nums, target);
        return new int[]{first, last};
    }

    private int searchLeftMost(int[] nums, int target) {
        int left = 0;
        int right = nums.length;
        int candidate = -1;
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (target < nums[mid]) {
                right = mid;
            } else if (target > nums[mid]) {
                left = mid + 1;
            } else {
                candidate = mid;
                right = mid;
            }
        }
        return candidate;
    }

    private int searchRightMost(int[] nums, int target) {
        int left = 0;
        int right = nums.length;
        int candidate = -1;
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (target < nums[mid]) {
                right = mid;
            } else if (target > nums[mid]) {
                left = mid + 1;
            } else {
                candidate = mid;
                left = mid + 1;
            }
        }
        return candidate;
    }
    public static void main(String[] args) {
        LC34 alg = new LC34();
        System.out.println(Arrays.toString(alg.searchRange(new int[]{5, 7, 7, 8, 8, 10}, 8)));
        System.out.println(Arrays.toString(alg.searchRange(new int[]{5, 7, 7, 8, 8, 10}, 6)));
        System.out.println(Arrays.toString(alg.searchRange(new int[0], 0)));
    }
}
